/**
 * 新增、编辑、删除、更新 读取 配置文件
*/
const fs = window.preload.fs;
import { assignment } from '../base/common.js';

function getProject(){
    return eval("(" + localStorage.getItem('projectConfig') + ")").nowProject;
}

async function createNativeFile(name){
    let nowProject = getProject();
    try{
        await fs.copySync(`${window.preload.dirname}output/template/json/blank.json`,`${window.preload.dirname}output/${nowProject.id}/json/${name}.json`);
        return { code:0,message:"新建成功" }
    } catch(err) {
        return { code:0,message:"新建失败" }
    }
}
//修改模版
async function changeNativeTem(item,type){
    let nowProject = getProject();
    const result = await fs.readFile(`${window.preload.dirname}output/template/json/${type}.json`,'utf8');
    let useResult = eval('(' + result + ')');
    await fs.writeJsonSync(`${window.preload.dirname}output/${nowProject.id}/json/${item.name}.json`, useResult)
}

//修改json内数据
async function editNativeFile(item,params){
    let nowProject = getProject();
    //修改json文件,
    const result = await fs.readFile(`${window.preload.dirname}output/${nowProject.id}/json/${item.name}.json`,'utf8');
    let useResult = eval('(' + result + ')');

    if(typeof params.type != 'undefined'){
        useResult.type = params.type;
    }

    if(typeof params.area != 'undefined'){
        assignment(params.area,useResult.area);
    }
    await fs.writeJsonSync(`${window.preload.dirname}output/${nowProject.id}/json/${item.name}.json`, useResult)
}

//读取
async function readJson(item){
    let nowProject = getProject();
    const result = await fs.readFile(`${window.preload.dirname}output/${nowProject.id}/json/${item.name}.json`,'utf8');
    let useResult = eval('(' + result + ')');
    return useResult;
}

async function readTemplateJson(item){
    const result = await fs.readFile(`${window.preload.dirname}output/template/json/${item.name}.json`,'utf8');
    let useResult = eval('(' + result + ')');
    return useResult;
}

export{
    createNativeFile,
    editNativeFile,
    readJson,
    changeNativeTem,
    readTemplateJson
}